﻿using System.Web;
using System.IO;
using System;
using Token.Piker.Common;
using Token.Util;
using System.Web.SessionState;

namespace Token.Piker.Web.Admin.NewsAlbum
{
    /// <summary>
    /// UploadNewsPhoto 的摘要说明
    /// </summary>
    public class UploadNewsPhoto : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            UploadPhoto(context);
        }

        private void UploadPhoto(HttpContext context)
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            string news_album_id = context.Request.Params["news_album_id"];
            string uploadPath = "~/Admin/uploads/newsphoto/" + news_album_id + "/";
            string serverPath = HttpContext.Current.Server.MapPath(uploadPath);
            bool flag = false;
            if (file != null)
            {
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }

                Token.Piker.Model.NewsPhoto model = CreateCompressImg(uploadPath, file);
                model.Album = int.Parse(news_album_id);
                model.Flag = 0;

                if (context.Session["AlbumCover"] == null)
                {
                    int id = int.Parse(news_album_id);
                    Token.Piker.DAL.NewsAlbumDAL newsAlbumDAL = new Token.Piker.DAL.NewsAlbumDAL();
                    Token.Piker.Model.NewsAlbum album = newsAlbumDAL.GetModel(id);
                    if (string.IsNullOrEmpty(album.CoverURL))
                    {
                        album.CoverURL = model.CompressUrl_1;
                        newsAlbumDAL.Update(album);
                    }
                    context.Session["AlbumCover"] = album.CoverURL;
                }

                int pid = new Token.Piker.DAL.NewsPhotoDAL().Add(model);
                if (pid > 0)//如果正确插入图片表
                {
                    flag = true;
                }
                else
                {
                    new FileInfo(serverPath + file.FileName + Path.GetExtension(file.FileName)).Delete();
                }
            }
            context.Response.Write(flag ? "1" : "0");
        }

        private Token.Piker.Model.NewsPhoto CreateCompressImg(string uploadPath, HttpPostedFile file)
        {
            Stream fs = file.InputStream;
            System.Drawing.Image img = System.Drawing.Image.FromStream(fs);

            var size = ComputeSize(img);
            Stream[] photo_stream = new Stream[4];
            FileStream fs_src = null;
            string[] url = new string[5];
            Token.Piker.Model.NewsPhoto photo = new Token.Piker.Model.NewsPhoto();
            try
            {
                string hash = DateTime.Now.GetHashCode().ToString();
                url[0] = uploadPath + hash + Path.GetExtension(file.FileName);
                file.SaveAs(HttpContext.Current.Server.MapPath(url[0]));//保存源图
                for (int j = 0; j < 4; j++)   //挨个生成缩略图
                {
                    string Compress_path = uploadPath + hash + "_cop_" + j + Path.GetExtension(file.FileName);
                    photo_stream[j] = File.Create(HttpContext.Current.Server.MapPath(Compress_path), 1024);
                    
                    if (j > 1)//给第三和第四张图片加水印
                    {
                        if (j == 3)
                        {
                            img = System.Drawing.Image.FromStream(fs);
                        }
                        WaterMark.ImageWaterMarkPic(img, photo_stream[j], HttpContext.Current.Server.MapPath("~/Admin/images/Piker.png"), 3, 100, 7);
                        new ThumbnailImage().ToThumbnailImage(fs, photo_stream[j], size[1, j], size[0, j]);
                    }
                    else
                    {
                        //生成缩略图
                        new ThumbnailImage().ToThumbnailImage(fs, photo_stream[j], size[1, j], size[0, j]);
                    }
                    url[j + 1] = Compress_path;
                }

            }
            catch (System.Exception ex)
            {
                LogHelper.Log(ex.Message);
            }
            finally   //释放资源
            {
                if (fs != null)
                {
                    fs.Close();
                }
                if (fs_src != null)
                {
                    fs_src.Close();
                }
                for (int m = 0; m < photo_stream.Length; m++)
                {
                    if (photo_stream[m] != null)
                        photo_stream[m].Close();
                }
            }
            
            photo.SourceUrl = url[0];
            photo.CompressUrl_1 = url[1];
            photo.CompressUrl_2 = url[2];
            photo.CompressUrl_3 = url[3];
            photo.CompressUrl_4 = url[4];
            return photo;
        }

        /// <summary>
        /// 计算最适合的压缩大小 第一行为height 第二行为width
        /// </summary>
        /// <param name="img">img</param>
        /// <returns></returns>
        protected int[,] ComputeSize(System.Drawing.Image img)
        {
            int[,] ProSize = new int[2, 4];
            int[,] StandSize = GlobalConstants.Photo_Size;
            decimal width = img.Width,
                height = img.Height;
            //图片实际比例
            decimal rate = height / width;
            for (int i = 0; i < 4; i++)
            {
                if (StandSize[0, i] / StandSize[1, i] > rate)   //原图比标准比例要宽
                {
                    ProSize[0, i] = StandSize[0, i];
                    ProSize[1, i] = Convert.ToInt32(StandSize[0, i] / rate);
                }
                else
                {
                    ProSize[1, i] = StandSize[1, i];
                    ProSize[0, i] = Convert.ToInt32(StandSize[1, i] / rate);
                }
            }

            return ProSize;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}